# auto load
extends Node2D

## 点击交换

class DragData:

    var ivt: Inventory
    var index: int

    func _init(ivt_: Inventory, index_: int) -> void:
        ivt = ivt_
        index = index_


var drag_data: Array[DragData] = []
var item_texture_rect: TextureRect
var dragging: bool:
    set(value):
        dragging = value
        item_texture_rect.visible = dragging


func _ready() -> void:
    item_texture_rect = TextureRect.new()
    item_texture_rect.z_index = 99;
    item_texture_rect.custom_minimum_size = Vector2(16, 16)
    item_texture_rect.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
    item_texture_rect.mouse_filter = Control.MOUSE_FILTER_IGNORE
    get_tree().get_first_node_in_group("top_ui").add_child(item_texture_rect)


func _process(_delta: float) -> void:
    if not dragging: return
    
    item_texture_rect.global_position = get_global_mouse_position() - item_texture_rect.custom_minimum_size / 2

    if drag_data.size() == 2:
        InventoryManager.swap_items(
            drag_data[0].ivt, drag_data[0].index, drag_data[1].ivt, drag_data[1].index
        )
        drag_data.clear()
        dragging = false


func add_drag_data(ivt: Inventory, index: int) -> void:
    if drag_data.size() == 0 and ivt.list[index] == null:
        return
    drag_data.append(DragData.new(ivt, index))
    if drag_data.size() == 1:
        dragging = true
        item_texture_rect.texture = InventoryManager.get_item(ivt.list[index].id).icon
